<?php

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\store;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use Imi\Config;

/**
 * 普通商品订单
 * @Auth(name="token",nologin={"no"})
 * @Controller("/store.order/")
 */
class Order extends StoreOwner
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 获取我的主订单列表
     *
     * @param integer|null $page 1
     * @param integer|null $limit 10
     * @param string $status 订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
     * @param string $comment_status 评价状态:0=未评价,1=已评价
     * @param string $dispatch_status 发货状态:0=未发货,1=已发货,2=已收货
     * @param string $aftersale_status 售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成,3=全部
     * 
     * @return void
     * @Action
     */
    public function get_main_order_list(?int $page = 1, ?int $limit = 10, $status = null, $comment_status = null, $dispatch_status = null, $aftersale_status = null)
    {
        $this->init();
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $where['store_id'] = $this->store_id;

        if ($status)
            $where['status'] = $status;

        //评论
        if ($comment_status !== null) {
            if ($comment_status === '0') {
                $where['status'] = '1';
            }
            $where2['comment_status'] = $comment_status;
            $where2['store_id'] = $this->store_id;
            $order_ids = Db::name('order_item')->whereEx($where2)->fieldRaw('order_id')->distinct()->column('order_id');
            if ($order_ids)
                $where['id'] = ['in', $order_ids];
        }

        //售后
        if ($aftersale_status) {
            $where3['store_id'] = $this->store_id;
            if ($aftersale_status != '3') {
                $where3['aftersale_status'] = $aftersale_status;
            }

            $order_ids = Db::name('order_aftersale')->whereIsNull('deletetime')->whereEx($where3)->fieldRaw('order_id')->distinct()->column('order_id');
            if ($order_ids)
                $where['id'] = ['in', $order_ids];
        }
        // var_dump($where);
        // \Imi\Log\Log::info(date('H:i:s'));

        $list = Db::name('order')->whereEx($where)->page($page, $limit)->select()->getArray();
        foreach ($list as $key => &$val) {
            $val = $this->ChangeOrder($val);
        }
        return $this->success('ok', $list);
    }





    /**
     * 获取我的子订单列表
     *
     * @param integer|null $page 1
     * @param integer|null $limit 10
     * @param string $status 订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
     * @param string $comment_status 评价状态:0=未评价,1=已评价
     * @param string $dispatch_status 发货状态:0=未发货,1=已发货,2=已收货
     * @param string $aftersale_status 售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成,3=全部
     * @param string $order 订单号
     * @return void
     * @Action
     */
    public function get_order_item_list(?int $page = 1, ?int $limit = 10, $status = null, $comment_status = null, $dispatch_status = null, $aftersale_status = null, $order = null)
    {
        $this->init();
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $where['store_id'] = $this->store_id;



        $order_ids_arr = [];

        if ($order) {
            $where0['store_id'] = $this->store_id;
            $where0['order_sn'] = ['like', '%' . $order . '%'];
            $order_ids = Db::name('order')
                ->whereEx($where0)
                ->fieldRaw('id')
                ->distinct()
                ->column('id');
            if ($order_ids) {
                $order_ids_arr =  $order_ids;
            } else {
                // return $this->success('ok', []);
            }
            $where['and'] = ['goods_sku_text' => ['like', '%' . $order . '%'], 'or' => ['goods_title' => ['like', '%' . $order . '%']]];
            //$where['order_id'] = ['in', $order_ids];

        }



        if ($status !== null && $status != '') {
            var_dump('status', $status);
            $where1['status'] = $status;
            $where1['store_id'] = $this->store_id;
            $order_ids = Db::name('order')->whereEx($where1)->fieldRaw('id')->distinct()->column('id');
            // if ($order_ids)
            if ($order_ids) {
                $order_ids_arr = array_intersect($order_ids_arr, $order_ids);
            } else {
                return $this->success('ok', []);
            }
        }


        //评论
        if ($comment_status !== null && $comment_status != '') {
            if ($comment_status === '0') {
                $where2['status'] = '1';
                $where2['store_id'] = $this->store_id;
                $order_ids = Db::name('order')->whereEx($where2)->fieldRaw('id')->distinct()->column('id');
                if ($order_ids) {
                    $order_ids_arr = array_intersect($order_ids_arr, $order_ids);
                } else {
                    return $this->success('ok', []);
                }
            }
            $where['comment_status'] = $comment_status;
        }

        //售后
        // if ($aftersale_status) {

        //     if ($aftersale_status != '3') {
        //         $where['aftersale_status'] = $aftersale_status;
        //     } else {
        //         $where3['store_id'] = $this->store_id;
        //         $order_ids = Db::name('order_aftersale')->whereIsNull('deletetime')->whereEx($where3)->fieldRaw('order_id')->distinct()->column('order_id');
        //         if ($order_ids) {
        //             $order_ids_arr = array_intersect($order_ids_arr, $order_ids);
        //         } else {
        //             return $this->success('ok', []);
        //         }
        //     }


        //     // $where['order_id'] = ['in', $order_ids];
        //     // 
        // }else{

        // }
        $where['aftersale_status'] = '0';

        if ($dispatch_status != null && $dispatch_status != '') {
            $where['dispatch_status'] = $dispatch_status;
        }


        if ($order_ids_arr) {
            $where['order_id'] = ['in', array_unique($order_ids_arr)];
        }


        $list = Db::name('order_item')->whereEx($where)->page($page, $limit)->orderRaw('createtime desc')->select()->getArray();
        foreach ($list as $key => &$val) {
            $val = $this->ItemChangeOrder($val);
        }
        return $this->success('ok', $list);
    }







    /**
     * 获取售后订单列表
     *
     * @param integer|null $page 1
     * @param integer|null $limit 10
     * @param string $refund_status 退款状态:-1=拒绝退款,0=未退款,1=同意
     * @param string $dispatch_status 发货状态:0=未发货,1=已发货,2=已收货
     * @param string $aftersale_status 售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成,3=全部
     * @param string $order 订单号
     * @return void
     * @Action
     */
    public function get_order_aftersale_list(?int $page = 1, ?int $limit = 10, $refund_status = null, $dispatch_status = null, $aftersale_status = null, $order = null)
    {
        $this->init();
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $where['store_id'] = $this->store_id;


        //退款
        if ($refund_status !== null && $refund_status != '') {
            $where['refund_status'] = $refund_status;
        }

        //售后
        if ($aftersale_status !== null && $aftersale_status != '') {
            $where['aftersale_status'] = $aftersale_status;
        }
        //发货状态
        if ($dispatch_status != null && $dispatch_status != '') {
            $where['dispatch_status'] = $dispatch_status;
        }



        $list = Db::name('order_aftersale')->whereIsNull('deletetime')->whereEx($where)->page($page, $limit)->orderRaw('createtime desc')->select()->getArray();
        foreach ($list as $key => &$val) {
            $val = $this->ItemChangeAftersaleOrder($val);
        }
        return $this->success('ok', $list);
    }

    /**
     * 回复评论
     *
     * @param int $id 评论id
     * @param string $reply_content 回复内容
     * @Action
     * @return void
     */
    public function reply_comment($id, $reply_content = null)
    {
        $this->init();
        $where['id'] = $id;
        $where['store_id'] = $this->store_id;
        $comment = Db::name('goods_comment')->whereEx($where)->find();
        if (!$comment) {
            $this->error('没有该评论');
        }
        Db::name('goods_comment')->whereEx($where)->update(['reply_content' => $reply_content, 'replytime' => time()]);
    }




    protected function ItemChangeOrderDetail($val)
    {
        $val['user'] = $this->GetUserData2($val['user_id']);
        $val['order'] = Db::name('order')->where('id', '=', $val['order_id'])->find();
        $val['date'] = date('Y-m-d H:i:s', $val['createtime']);

        try {
            $where['order_item_id'] = $val['id'];
            $where['order_id'] = $val['order_id'];
            $comment = Db::name('goods_comment')->whereEx($where)->find();
            if ($comment) {
                $comment['date'] = date('Y-m-d H:i:s', $comment['createtime']);
                if ($comment['replytime'] > 0)
                    $comment['reply_date'] = date('Y-m-d H:i:s', $comment['replytime']);
                $val['comment'] = $comment;
            }
            if ($val['dispatch_time'] > 0)
                $val['dispatch_date'] = date('Y-m-d H:i:s', $val['dispatch_time']);
            if ($val['order']['paytime'] > 0)
                $val['order']['paydate'] = date('Y-m-d H:i:s', $val['order']['paytime']);
        } catch (\Throwable $th) {
            //throw $th;
        }

        return $val;
    }

    protected function ItemChangeOrder($val)
    {
        $val['user'] = $this->GetUserData2($val['user_id']);
        $val['order'] = Db::name('order')->where('id', '=', $val['order_id'])->find();
        if ($val['refund_status'] != '0') {
            $where3['type'] = 'refund';
            $where3['order_id'] = $val['id'];
            $val['order_aftersale'] = Db::name('order_aftersale')->whereIsNull('deletetime')->whereEx($where3)->find();
        }
        $val['date'] = date('Y-m-d H:i', $val['createtime']);

        return $val;
    }

    protected function ChangeOrder($val)
    {
        $val['user'] = $this->GetUserData2($val['user_id']);
        $val['order_item'] = Db::name('order_item')->where('order_id', '=', $val['id'])->select()->getArray();
        return $val;
    }

    protected function ChangeOrderDetail($val)
    {
        $val['user'] = $this->GetUserData2($val['user_id']);
        $val['order_item'] = Db::name('order_item')->where('order_id', '=', $val['id'])->select()->getArray();
        return $val;
    }

    /**
     * 售后
     *
     * @param [type] $val
     * @return void
     */
    protected function ItemChangeAftersaleOrder($val)
    {
        $val['user'] = $this->GetUserData2($val['user_id']);
        $val['order_item'] = Db::name('order_item')->where('id', '=', $val['order_item_id'])->find();
        $val['order'] = Db::name('order')->where('id', '=', $val['order_id'])->find();
        return $val;
    }










    // /**
    //  * 单个评价
    //  *
    //  * @param int $order_id 总订单id
    //  * @param integer|null $order_item_id
    //  * @param string $content 评价内容
    //  * @param integer $level 评分等级
    //  * @param string $images 图片
    //  * @return void
    //  * @Action
    //  */
    // public function comment(?int $order_id = null, ?int $order_item_id = null, $content = null, $level = 5, $images = null)
    // {
    //     $where['order_id'] = $order_id;
    //     $where['id'] = $order_item_id;
    //     $where['store_id'] = $this->store_id;

    //     $res = Db::name('order_item')->whereEx($where)->find();
    //     var_dump($where);
    //     if ($res) {
    //         if ($res['comment_status'] == '1')
    //             return $this->error('您已评论过该订单');


    //         $data['order_id'] = $order_id;
    //         $data['order_item_id'] = $order_item_id;
    //         $data['store_id'] = $this->store_id;
    //         $order =  Db::name('order_item')->where('id', '=', $order_item_id)->find();
    //         $data['goods_id'] = $order['goods_id'];
    //         $data['goods_sku_price_id'] = $order['goods_sku_price_id'];
    //         $data['store_id'] = $order['store_id'];

    //         $data['level'] = $level;
    //         $data['content'] = $this->Xss($content);
    //         if (!empty($images))
    //             $data['images'] = $images;
    //         $data['status'] = 'show'; //hidden
    //         $data['createtime'] = time();

    //         Db::name('goods_comment')->insert($data);
    //         Db::name('order_item')->where('id', '=', $res['id'])->update(['comment_status' => '1']);
    //         return $this->success('评论成功');
    //     } else {
    //         return $this->error('没有该订单');
    //     }

    //     return $this->error('您已评论');
    // }



    /**
     * 子订单详情👔
     *
     * @param int $id 订单id
     * @return void
     * @Action
     */
    public function order_item_detail($id)
    {
        $this->init();

        $where['id'] = $id;
        $where['store_id'] =  $this->store_id;
        $order = Db::name('order_item')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->select()->get();
        if ($order) {
            $order = $this->ItemChangeOrderDetail($order);
        }



        return $this->success('order', $order);
    }




    /**
     * 主订单详情👔
     *
     * @param int $id 订单id
     * @return void
     * @Action
     */
    public function main_order_detail($id)
    {
        $this->init();

        $where['id'] = $id;
        $where['store_id'] =  $this->store_id;
        $order = Db::name('order')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->select()->get();
        if ($order) {
            $order = $this->ChangeOrderDetail($order);
        }



        return $this->success('order', $order);
    }


    /**
     * 取消总订单
     *
     * @param int $order_id 总订单id
     * @return void
     * @Action
     */
    public function cancel_order_total(?int $order_id)
    {
        $this->init();
        $this->CancelTotalOrder($order_id);
        return $this->success('取消成功', $order_id);
    }

    /**
     * 取消订单
     *
     * @param int $order_id 订单id
     * @return void
     */
    public function cancel_order($order_id)
    {
    }



    /**
     * 发货
     *
     * @param int $id 子订单id
     * @param string $express_name 快递公司
     * @param string $express_no 快递编号
     * @return void
     * @Action
     */
    public function dispatch_order_item($id, $express_name = null, $express_no = null)
    {
        $this->init();
        
        $where['id'] = $id;
        $where['store_id'] =  $this->store_id;
        $order_item = Db::name('order_item')->whereEx($where)->find();
        if ($order_item['refund_status'] == '2') {
            return $this->error('你已经退款');
        }

        if ($order_item['dispatch_status'] == '2') {
            return $this->error('用户已收货');
        }

        $where2['store_id'] = $this->store_id;
        $where2['order_id'] = $order_item['order_id'];
        // $where2['dispatch_status'] = '0';

        //退款状态:-1=拒绝退款,0=无,1=申请中,2=同意
        if ($order_item['refund_status'] == '1' || $order_item['refund_status'] == '2') {
            return $this->error('该订单有退款状态');
        }
        //
        // $where2['refund_status'] = '0';

        $update_list = Db::name('order_item')->whereEx($where)->select()->getArray();
        if (sizeof($update_list) < 1) {
            return $this->error('没有可用发货的订单', $where);
        }

        $update['dispatch_status'] = '1';
        $update['express_name'] = $express_name;
        $update['express_no'] = $express_no;
        $update['updatetime'] = time();

        $快递包裹['user_id']  = $order_item['user_id']; //用户
        $快递包裹['store_id']  = $order_item['store_id']; //店铺
        $快递包裹['order_id']  = $order_item['order_id']; //订单
        $快递包裹['order_item_id']  = $order_item['id']; //子订单
        $快递包裹['express_name']  = $express_name; //快递公司
        $快递包裹['express_no']  = $express_no; //快递单号
        $快递包裹['createtime']  = time();
        $快递包裹['updatetime']  = time();
        $快递包裹['status']  = '1'; //状态:1=卖家正常发货,2=用户售后,3=卖家换货
        $this->AddOrderExpress($快递包裹);

        //更新订单的操作记录
        $order = Db::name('order')->where('id', '=', $order_item['order_id'])->find();
        foreach ($update_list as $val) {
            $操作记录['order_id'] = $val['order_id'];
            $操作记录['order_item_id'] = $val['id'];
            $操作记录['oper_type'] = 'store';
            $操作记录['oper_id'] = $this->store_id;
            // $操作记录['order_status'] = $order['status'];//订单状态
            $操作记录['dispatch_status'] = '1'; //发货状态:0=未发货,1=已发货,2=已收货
            // $操作记录['comment_status'] = $val['comment_status']; //评价状态:0=未评价,1=已评价
            // $操作记录['aftersale_status'] = $val['aftersale_status']; //售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成
            // $操作记录['refund_status'] = '-1'; //退款状态:-1=拒绝退款,0=未退款,1=同意
            $操作记录['remark'] = '商家发货';
            $操作记录['createtime'] = time();
            $操作记录['updatetime'] = time();
            $this->UpdateOrderAction($操作记录);
        }


        //把同店铺的发货
        Db::name('order_item')->whereEx($where)->update($update);

        return $this->success('发货成功', sizeof($update_list));
    }
}
